#!/usr/bin/env python
# -*- coding:utf-8 -*-

from bottle import Bottle
from bottle import request, response

from comm.beans.SysDictObj import SysDictObj
from conn.MyPagerFactory import MyPager

SysDictAdm = Bottle()


@SysDictAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@SysDictAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class SysDictRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "991": "处理参数错误, 请填写 %s",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    conn = None
    times_array = []

    def __init__(self, conn):
        SysDictRoute.conn = conn
        return

    @staticmethod
    @SysDictAdm.get('/fetch')
    def fetch():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        try:
            count_sql = f" SELECT count(`id`) FROM `sys_dict` WHERE 1=1 %s"
            fetch_sql = f" SELECT `id`, `key`, `key_eng`, `col`, `val`, `add_time` " \
                        f" FROM `sys_dict` WHERE 1=1 %s "
            where_sql = ""
            if len(params['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`key`,`key_eng`) like CONCAT('%',\'{params['key']}\','%') "
            int_begin = 0
            if int(params['pageNum']) > 1:
                int_begin = (int(params['pageNum']) - 1) * int(params['pageSize'])
            elif int(params['pageNum']) == 1:
                int_begin = 0 * int(params['pageSize'])
            where_sql_no_limit = where_sql
            where_sql_limit = where_sql_no_limit + f" ORDER BY `col` ASC,`add_time` DESC LIMIT {int_begin}, {int(params['pageSize'])}"
            data_total = SysDictRoute.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = SysDictRoute.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [SysDictObj.load_db_2_dict(data=item) for item in data_list]
            _pages = MyPager.make_pager(id="table_projects_msg", res=items, page_size=int(params['pageSize']),
                                        data_total=data_total[0][0], single_pager=False)
            return {'code': 200, 'data': _pages, 'message': ""}
        except Exception as e:
            return {'code': 99, 'data': None, 'message': SysDictRoute.ERROR_CODE["99"]}

    @staticmethod
    @SysDictAdm.get('/fetchOne')
    def fetch_one():
        id = request.params.id
        if int(id)== 0:
            return {'code': 200, 'data': {}, 'message': ""}
        fetch_sql = f" SELECT `id`, `key`, `key_eng`, `col`, `val`, `add_time` " \
                    f" FROM `sys_dict` WHERE 1=1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = SysDictRoute.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                one_data = [SysDictObj.load_db_2_dict(item) for item in items][0]
                return {'code': 200, 'data': one_data, 'message': ""}
        except Exception as e:
            print(e)
        return {'code': 99, 'data': None, 'message': SysDictRoute.ERROR_CODE["99"]}

    @staticmethod
    @SysDictAdm.get('/fetchCalGups')
    def fetch_cal_gup():
        fetch_sql = f" SELECT `id`, `key`, `key_eng`, `col` " \
                    f" FROM `sys_dict` WHERE 1=1 " \
                    f" GROUP BY `col` "
        try:
            items = SysDictRoute.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                sysDictOpts = [{"key": item[0], "lable": item[3], "value": item[3]} for item in items]
                return {'code': 200, 'data': sysDictOpts, 'message': ""}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    @staticmethod
    @SysDictAdm.post('/add')
    def add():
        from datetime import datetime
        if request.json is not None:
            sysDict = request.json['data']
            # 获取当前时间
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            add_check = SysDictRoute.count_one(id=sysDict['id'])
            if add_check:
                return {'code': 100, 'data': None, 'message': SysDictRoute.ERROR_CODE["100"]}
            try:
                sysDict['add_time'] = current_time
                insert_sql = f" INSERT INTO `sys_dict` ({SysDictObj.to_string(False)}) " \
                             " VALUES ( %s )" % SysDictObj.concat_datas(sysDict)
                SysDictRoute.conn.sql_commit(insert_sql)
                return {'code': 200, 'data': sysDict, 'message': ""}
            except Exception as e:
                print(e)
            return {'code': 100, 'data': None, 'message': SysDictRoute.ERROR_CODE["100"]}

    @staticmethod
    @SysDictAdm.post('/update')
    def update():
        from datetime import datetime
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if request.json is not None:
            sysDict = request.json['data']
            add_check = SysDictRoute.count_one(id=sysDict['id'])
            if not add_check:
                return {'code': 109, 'data': None, 'message': SysDictRoute.ERROR_CODE["109"]}
            try:
                sysDict['add_time']= current_time
                update_str = SysDictObj.split_params(sysDict)
                update_sql = f" UPDATE `sys_dict` SET %s WHERE `id`= \'%s\'" % (update_str, sysDict['id'])
                SysDictRoute.conn.sql_commit(update_sql)
                return {'code': 200, 'data': None, 'message': ""}
            except Exception as e:
                print(e)
            return {'code': 102, 'data': None, 'message': SysDictRoute.ERROR_CODE["102"]}

    @staticmethod
    @SysDictAdm.get('/drop')
    def drop():
        from datetime import datetime
        id = request.params.id
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = SysDictRoute.count_one(id=id)
        if not add_check:
            return {'code': 109, 'data': None, 'message': SysDictRoute.ERROR_CODE["109"]}
        try:
            execute_SQL = f" DELETE FROM `sys_dict` WHERE `id` = \'{id}\'"
            SysDictRoute.conn.sql_commit(execute_SQL)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {'code': 103, 'data': None, 'message': SysDictRoute.ERROR_CODE["103"]}

    def count_one(id) -> bool:
        fetch_sql = f"SELECT count(`id`) FROM `sys_dict` WHERE 1 = 1 AND `id` = \'{id}\'"
        try:
            if id == 0:
                return False
            items = SysDictRoute.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}
